package com.cmd.project.controller;

import com.alibaba.fastjson2.JSONObject;
import com.cmd.common.core.controller.BaseController;
import com.cmd.common.core.domain.AjaxResult;
import com.cmd.framework.config.WxAppConfig;
import com.cmd.project.domain.WxConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.util.UUID;

/**
 * @author zhangshuai
 * @date 2024/11/16
 */
@RestController
@RequestMapping("/project/app")
public class AppController extends BaseController {


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WxAppConfig wxAppConfig;





    @PostMapping("/getWxConfig")
    public AjaxResult getWxConfig(@RequestBody WxConfig w) {
        String appId = wxAppConfig.getAppId();
        String appSecret = wxAppConfig.getAppSecret();

        String tokenData =
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                        + appId
                        + "&secret="
                        + appSecret;
        String response = restTemplate.getForObject(tokenData, String.class);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String accessToken = jsonObject.getString("access_token");
        System.out.println(response);

        String ticketUrl =
                "https://api.weixin.qq.com/cgi-bin/ticket/getticket?"
                        + "access_token="
                        + accessToken
                        + "&type=jsapi";
        String resp = restTemplate.getForObject(ticketUrl, String.class);
        JSONObject jsonObject1 = JSONObject.parseObject(resp);

        String ticket = String.valueOf(jsonObject1.get("ticket"));
        String nonceStr = UUID.randomUUID().toString();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String string1 =
                new StringBuilder("jsapi_ticket=")
                        .append(ticket)
                        .append("&noncestr=")
                        .append(nonceStr)
                        .append("&timestamp=")
                        .append(timestamp)
                        .append("&url=")
                        .append(w.getUrl())
                        .toString();
        // 得到签名
        String signature = encryptSHA(string1);
        WxConfig wxConfig = new WxConfig();

        wxConfig.setDebug(true);
        wxConfig.setAppId(wxAppConfig.getAppId());
        wxConfig.setNonceStr(nonceStr);
        wxConfig.setUrl(w.getUrl());
        wxConfig.setSignature(signature);
        wxConfig.setTimestamp(timestamp);
        wxConfig.setTicket(ticket);
        wxConfig.setJsApiList(new String[]{"scanQRCode"});

        return success(wxConfig);
    }

    /**
     * sha
     */
    private static String encryptSHA(String signStr) {
        StringBuffer hexValue = new StringBuffer();
        try {
            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            byte[] byteArray = signStr.getBytes("UTF-8");
            byte[] md5Bytes = sha.digest(byteArray);
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return hexValue.toString();
    }


}
